package HTTP

import (
	"emb/emb_server/SQL/util"
	"emb/emb_server/logs"
	"net/http"
)

type friengInfo struct {
	NickName string
	Icon     string
	Custom   string
}

// request : objectID  string
// respon : friengInfo
// { nickName string
// icon     string
// custom   string}
func getObjectData(w http.ResponseWriter, r *http.Request) {

	var code = Success
	var info = "success"
	var information interface{}

	defer func() {
		writeResult(w, code, info, information)
	}()

	config(w, r)

	err := r.ParseForm()
	if err != nil {
		code = errParseForm
		logs.Print("From:getObjectData.ParseForm---", err.Error())
		info = "From:getObjectData.ParseForm---" + err.Error()
		return
	}

	id := r.Form["objectID"]
	if id == nil {
		code = errEmtpyID
		logs.Print("From:getObjectData.ParseForm:---" + err.Error())
		info = "From:getObjectData:---objectID输入有误,不全是数字或为空"
		return
	}
	ok, code, info := checkOutId(id[0])
	if !ok {
		return
	}

	info, information, ok = getDbData(id[0])
	if !ok {
		code = errDBQueryFailed
	}

}

//从数据库数据获取好友信息数据
func getDbData(id string) (string, interface{}, bool) {

	var nickName, icon string
	var custom []byte
	var friengInfo friengInfo
	var information []interface{}
	info := "success"

	db := util.GetDb()
	sql := "select nickname,icon,custom from objects where id = $1"
	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		logs.Print("From:getObjectData.Prepare---", err.Error())
		info = "From:getObjectData.Prepare---" + err.Error()
		return info, nil, false
	}
	if id == "" {
		logs.Print("From:getObjectData---- Id is null")
		info = "From:getObjectData---- Id is null"
		return info, nil, false
	}

	rows, err := stmt.Query(id)
	defer rows.Close()
	if err != nil {
		logs.Print("From:getObjectData.Query---", err.Error())
		info = "From:getObjectData.Query---" + err.Error()
		return info, nil, false
	}

	if rows.Next() == false {
		logs.Print("From:getObjectData---- find nothing")
		info = "From:getObjectData---- find nothing"
		return info, nil, false
	}

	err = rows.Scan(&nickName, &icon, &custom)
	if err != nil {
		logs.Print("From:getObjectData.Scan---", err.Error())
		info = "From:getObjectData.Scan---" + err.Error()
		return info, nil, false
	}

	friengInfo.NickName = nickName
	friengInfo.Icon = icon
	friengInfo.Custom = string(custom)
	information = append(information, friengInfo)

	return info, friengInfo, true
}
